package cn.initcap.social.weixin.config;

import cn.initcap.properties.SecurityProperties;
import cn.initcap.properties.WeixinProperties;
import cn.initcap.social.view.InitcapConnectView;
import cn.initcap.social.weixin.connect.WeixinConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.social.SocialAutoConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.web.servlet.View;

/**
 * 微信登录配置，@ConditionalOnProperty的意思是查找配置文件中有没有配置以initcap.security.social.weixin
 * 为前缀，名称为app-id的值，如果配置才会将ConnectionFactory这个bean放入spring
 *
 * @author initcap
 * @date 2018/5/19 PM6:02
 */
@Configuration
@ConditionalOnProperty(prefix = "initcap.security.social.weixin", name = "app-id")
public class WeixinAutoConfiguration extends SocialAutoConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    protected ConnectionFactory<?> createConnectionFactory() {
        WeixinProperties weixinConfig = securityProperties.getSocial().getWeixin();
        return new WeixinConnectionFactory(weixinConfig.getProviderId(), weixinConfig.getAppId(),
                weixinConfig.getAppSecret());
    }

    /**
     * @return
     * @ConditionalOnMissingBean 的作用是当有人创建了：name = "weixinConnectedView"的bean
     * 此处的bean就会被替代。
     * 绑定解除绑定视图，
     */
    @Bean({"connect/weixinConnect", "connect/weixinConnected"})
    @ConditionalOnMissingBean(name = "weixinConnectedView")
    public View weixinConnectedView() {
        return new InitcapConnectView();
    }

}
